package com.hbnu.mysql.Cart;

import com.hbnu.mysql.User.LRService;

import java.math.BigDecimal;
import java.sql.*;
import java.util.Scanner;

/*
 * @author zouting
 * @Date 2025-11-26-10:46
 *
 */public class OrderService {
     private final String loginUser;
     private final Scanner scanner;

     public OrderService(String loginUser) {
         this.loginUser = loginUser;
         this.scanner = new Scanner(System.in);
     }

     /*
     * 创建订单*/
     public void createOrder() {
         String sql = "SELECT COUNT(*) as item_count, " +
                 "SUM(f.price * c.quantity) as total_amount "  +
                 "FROM tb_cart c "  +
                 "JOIN tb_flower f ON c.fid = f.fid "  +
                 "WHERE c.username = ?";
         try (Connection connection = LRService.getConnection();
              PreparedStatement cpreparedStatement = connection.prepareStatement(sql)){

             cpreparedStatement.setString(1, loginUser);
             ResultSet resultSet = cpreparedStatement.executeQuery();

             if (resultSet.next() && resultSet.getInt("item_count") > 0){
                 double total = resultSet.getDouble("total_amount");
                 System.out.println("订单总金额为：" + total);
                 System.out.println("是否确认创建订单？(y/n)");
                 String confirm = scanner.nextLine().trim();

                 if ("y".equalsIgnoreCase(confirm)){
                     //获取用户地址和手机号
                     String userInfoSql = "SELECT address, phone FROM tb_user WHERE username = ?";
                     try (PreparedStatement userpreparedStatement = connection.prepareStatement(userInfoSql)){
                         userpreparedStatement.setString(1, loginUser);
                         ResultSet userResultSet = userpreparedStatement.executeQuery();
                         String address = "";
                         String phone = "";
                         if (userResultSet.next()){
                             address = userResultSet.getString("address");
                             phone = userResultSet.getString("phone");
                         }
                         //创建订单
                         createOrder(connection, total, address, phone);
                     }
                 }
             }else {
                 System.out.println("购物车为空，无法创建订单");
             }
         }catch (Exception e){
             System.out.println("创建订单失败：" + e.getMessage());
             e.printStackTrace();
         }
     }

    /**
     * 创建订单（事务处理）
     */
    private void createOrder(Connection conn, double totalAmount, String address, String phone) throws SQLException {
        conn.setAutoCommit(false);

        try {
            // 1. 插入订单主表
            String orderSql = "INSERT INTO tb_orders (username, total_amount, address, phone) VALUES (?, ?, ?, ?)";
            int orderId;

            try (PreparedStatement orderPs = conn.prepareStatement(orderSql, Statement.RETURN_GENERATED_KEYS)) {
                orderPs.setString(1, loginUser);
                orderPs.setDouble(2, totalAmount);
                orderPs.setString(3, address);
                orderPs.setString(4, phone);
                orderPs.executeUpdate();

                // 获取生成的订单ID
                ResultSet rs = orderPs.getGeneratedKeys();
                if (rs.next()) {
                    orderId = rs.getInt(1);
                } else {
                    throw new SQLException("创建订单失败，无法获取订单ID");
                }
            }

            // ========== 新增：保存订单商品明细 ==========
            String itemSql = "INSERT INTO tb_order_items (order_id, fid, fname, quantity, price, subtotal) " +
                    "SELECT ?, c.fid, f.fname, c.quantity, f.price, (f.price * c.quantity) " +
                    "FROM tb_cart c JOIN tb_flower f ON c.fid = f.fid " +
                    "WHERE c.username = ?";

            try (PreparedStatement itemPs = conn.prepareStatement(itemSql)) {
                itemPs.setInt(1, orderId);
                itemPs.setString(2, loginUser);
                int itemsCount = itemPs.executeUpdate();
                System.out.println("保存了 " + itemsCount + " 件商品明细");
            }

            // 2. 更新库存（从购物车中的商品）
            String updateStockSql = "UPDATE tb_flower f " +
                    "JOIN tb_cart c ON f.fid = c.fid " +
                    "SET f.stock = f.stock - c.quantity " +
                    "WHERE c.username = ?";

            try (PreparedStatement updatePs = conn.prepareStatement(updateStockSql)) {
                updatePs.setString(1, loginUser);
                updatePs.executeUpdate();
            }

            // 3. 清空购物车
            String clearCartSql = "DELETE FROM tb_cart WHERE username = ?";
            try (PreparedStatement clearPs = conn.prepareStatement(clearCartSql)) {
                clearPs.setString(1, loginUser);
                clearPs.executeUpdate();
            }

            // 提交事务
            conn.commit();
            System.out.println("订单创建成功！订单号: " + orderId);
            System.out.println("请及时完成支付！");

        } catch (SQLException e) {
            // 回滚事务
            conn.rollback();
            throw e;
        } finally {
            conn.setAutoCommit(true);
        }
    }

    /**
     * 查看用户订单列表
     */
    public void viewUserOrders() {
        String sql = "SELECT order_id, total_amount, status, create_time " +
                "FROM tb_orders WHERE username = ? ORDER BY create_time DESC";

        try (Connection conn = LRService.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {

            ps.setString(1, loginUser);
            ResultSet rs = ps.executeQuery();

            System.out.println("\n========== 我的订单 ==========");
            System.out.printf("%-10s %-12s %-10s %-20s\n",
                    "订单号", "总金额", "状态", "创建时间");
            System.out.println("------------------------------------------------------------");

            boolean hasOrders = false;
            while (rs.next()) {
                hasOrders = true;
                System.out.printf("%-10d %-12.2f %-10s %-20s\n",
                        rs.getInt("order_id"),
                        rs.getDouble("total_amount"),
                        rs.getString("status"),
                        rs.getTimestamp("create_time"));
            }

            if (!hasOrders) {
                System.out.println("暂无订单");
            }

        } catch (Exception e) {
            System.out.println("获取订单失败: " + e.getMessage());
        }
    }

    /**
     * 查看订单详情
     */
    public void viewOrderDetail() {
        System.out.print("请输入订单号: ");
        String orderIdStr = scanner.nextLine().trim();

        try {
            int orderId = Integer.parseInt(orderIdStr);
            // 首先验证订单属于当前用户
            String verifySql = "SELECT username FROM tb_orders WHERE order_id = ?";
            try (Connection conn = LRService.getConnection();
                 PreparedStatement verifyPs = conn.prepareStatement(verifySql)) {

                verifyPs.setInt(1, orderId);
                ResultSet verifyRs = verifyPs.executeQuery();

                if (!verifyRs.next() || !loginUser.equals(verifyRs.getString("username"))) {
                    System.out.println("订单不存在或无权查看");
                    return;
                }
            }

            // 显示订单基本信息
            String orderSql = "SELECT order_id, total_amount, status, address, phone, create_time,pay_time " +
                    "FROM tb_orders WHERE order_id = ?";

            try (Connection conn = LRService.getConnection();
                 PreparedStatement orderPs = conn.prepareStatement(orderSql)) {

                orderPs.setInt(1, orderId);
                ResultSet orderRs = orderPs.executeQuery();

                if (orderRs.next()) {
                    System.out.println("\n========== 订单详情 ==========");
                    System.out.println("订单号: " + orderRs.getInt("order_id"));
                    System.out.println("总金额: ￥" + orderRs.getDouble("total_amount"));
                    System.out.println("状态: " + orderRs.getString("status"));
                    System.out.println("收货地址: " + orderRs.getString("address"));
                    System.out.println("联系电话: " + orderRs.getString("phone"));
                    System.out.println("创建时间: " + orderRs.getTimestamp("create_time"));
                    Timestamp payTime = orderRs.getTimestamp("pay_time");
                    if (payTime != null) {
                        System.out.println("支付时间: " + payTime);
                    }
                    System.out.println("==============================");
                    System.out.println("注：详细商品信息请在购物车历史中查看");

                }

            }

        } catch (NumberFormatException e) {
            System.out.println("请输入有效的订单号");
        } catch (Exception e) {
            System.out.println("获取订单详情失败: " + e.getMessage());
        }
    }


    /*
     * 处理订单支付
     * @param orderId 订单ID
     */
    public void payOrder(String orderId) {
        try {
            // 验证订单是否存在且属于当前用户
            String checkSql = "SELECT status, total_amount FROM tb_orders WHERE order_id = ? AND username = ?";
            try (Connection conn = LRService.getConnection();
                 PreparedStatement ps = conn.prepareStatement(checkSql)) {
                ps.setString(1, orderId);
                ps.setString(2, loginUser);
                ResultSet rs = ps.executeQuery();

                if (rs.next()) {
                    String status = rs.getString("status");
                    BigDecimal amount = rs.getBigDecimal("total_amount");

                    if ("待支付".equals(status)) {
                        // 模拟支付处理
                        System.out.println("订单金额: ¥" + amount);
                        System.out.println("请选择支付方式:");
                        System.out.println("1. 支付宝");
                        System.out.println("2. 微信支付");
                        System.out.println("3. 银行卡支付");
                        System.out.print("请选择(1-3): ");

                        String payChoice = scanner.nextLine().trim();
                        if ("1".equals(payChoice) || "2".equals(payChoice) || "3".equals(payChoice)) {
                            // 更新订单状态为已支付，并设置支付时间
                            String updateSql = "UPDATE tb_orders SET status = '已支付', pay_time = NOW() WHERE order_id = ?";
                            try (PreparedStatement updatePs = conn.prepareStatement(updateSql)) {
                                updatePs.setString(1, orderId);
                                int rowsAffected = updatePs.executeUpdate();

                                if (rowsAffected > 0) {
                                    System.out.println("支付成功！订单状态已更新。");
                                } else {
                                    System.out.println("支付失败，请稍后重试。");
                                }
                            }
                        } else {
                            System.out.println("支付取消或选择无效。");
                        }
                    } else if ("已支付".equals(status)) {
                        System.out.println("该订单已完成支付。");
                    } else {
                        System.out.println("订单状态不支持支付操作。");
                    }
                } else {
                    System.out.println("订单不存在或不属于您。");
                }
            }
        } catch (Exception e) {
            System.out.println("支付处理失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

}


